"""
根据drg分组中的icd10码查缺
"""
import json
import re
import common

TAG = "Drg2"
FIELDS = ["IcdCode"]

CHECK_TAG = 'Icd10'
CHECK_FIELDS = ['Code','Name']

server = common.ServerDebug

def export_drg_codes():
    print('Loading value set ...')
    data = common.export_fv(tag="Icd10", field="Code", print_res=False, server=common.ServerDebug)
    print('... Done')
    return json.loads(data)

def check():
    fv_arm = export_drg_codes()
    fv_set = fv_arm['data']
    print(len(fv_set))
    last_index = 0
    has_more = True
    page_index = 1
    missing_codes = []
    while has_more:
        query_message = {
            "fields": FIELDS,
            "pageIndex": page_index,
            "pageSize": 200,
            "lastIndex": last_index,
        }
        query_message = json.dumps(query_message, ensure_ascii=False)
        # print(query_message)
        arm = common.page(TAG, query_message, server=server)
        arm = json.loads(arm)
        last_index = arm['data']['lastIndex']
        has_more = len(arm['data']['data']) >= 200
        for record in arm['data']['data']:
            code = record['IcdCode']
            if common.is_icd10_code(code) and not code in fv_set and not code in missing_codes:
                missing_codes.append(code)
        page_index += 1
    print(len(missing_codes)," missing codes",)
    return missing_codes

def fill(missing_codes):
    filtered_lines = []
    added_onece_codes = []
    icd_10_code_pattern = re.compile(r'^[A-Z]\d+(\.\d+)(x\d+)*(\+\S+\*)*')
    with open('out/drg.txt', 'r', encoding='utf-8') as file:
        for line in file:
            match = re.search(icd_10_code_pattern, line.strip())
            if match:
                icd_code = match.group()  # 使用group()方法提取匹配结果
                if icd_code in missing_codes and icd_code not in added_onece_codes:
                    filtered_lines.append(line)
                    added_onece_codes.append(icd_code)
    print(len(filtered_lines), "filled", )
    return filtered_lines

def append_to_icd10(lines):
    records = []
    for line in lines:
        ary = line.strip().split()
        records.append({
            CHECK_FIELDS[0]: ary[0],
            CHECK_FIELDS[1]: ary[1]
        })
        if len(records) % 100 == 0:
            msg = json.dumps({
                "fields": CHECK_FIELDS,
                "records": records
            }, ensure_ascii=False)
            print(msg)
            common.batch_add(CHECK_TAG, msg, server=server)
            records.clear()
    if len(records) > 0:
        msg = json.dumps({
            "fields": CHECK_FIELDS,
            "records": records
        }, ensure_ascii=False)
        print(msg)
        common.batch_add(CHECK_TAG, msg, server=server)
        records.clear()


if __name__ == "__main__":
    missing_codes = check()
    print(missing_codes)
    # lines = fill(missing_codes)
    # append_to_icd10(lines)